﻿using System.Collections.Generic;
using System.Data.Common;
using Jayden.Dll.Core.Persistence;
using Jayden.Dll.Core.Persistence.Data;
using Jayden.Dll.Core.Persistence.Data.SQLite;
using Jayden.Dll.Core.Persistence.Models;

namespace Jayden.Dll.Core.Membership
{
	public class SQLiteRoleDataAccess : SQLiteDataAccess<Role>, RoleDataAccess
	{
		public SQLiteRoleDataAccess(Configuration config, UnitOfWork uow, Entity entity) : base(config, uow, entity) { }

		public List<Role> FindAll(int page, int pageSize, out int totalRecords)
		{
			string countCommandText = Helper.GenerateCount(Entity.Table.TableName, null, null);
			using (DbCommandProxy countCommand = CreateCommand(countCommandText))
			{
				object countObject = countCommand.Command.ExecuteScalar();
				string countString = countObject == null ? "0" : countObject.ToString();
				totalRecords = int.Parse(countString);
			}
			string selectCommandText = Helper.GenerateSelect(null, Entity.Table.TableName, null, null, null, pageSize, page * pageSize);
			using (DbCommandProxy selectCommand = CreateCommand(selectCommandText))
			{
				using (DbDataReader reader = selectCommand.Command.ExecuteReader())
				{
					List<Role> roles = new List<Role>(EnumerateFromReader(reader));
					return roles;
				}
			}
		}

		public void DeleteByName(string roleName)
		{
			string deleteCommandText = Helper.GenerateDelete(Entity.Table.TableName, "RoleName=@RoleName");
			using (DbCommandProxy deleteCommand = CreateCommand(deleteCommandText))
			{
				CreateParameter(deleteCommand, "RoleName", roleName);
				int count = deleteCommand.Command.ExecuteNonQuery();
			}
		}
	}
}
